<script setup lang="ts">
    import { defineProps, getCurrentInstance, ref, reactive, inject, toRefs } from 'vue';
    import { ElNotification, type FormInstance } from 'element-plus';
    import { Message } from '@element-plus/icons-vue';
    import { api } from '@/services/api';

    const msg: any = inject('message');
    const internalInstance = getCurrentInstance();
    const checkOldEmailFormRef = ref<FormInstance>();
    const checkNewEmailFormRef = ref<FormInstance>();

    // 属性
    const props = defineProps<{ visible: Boolean, oldEmail?: string }>();

    const { visible = false, oldEmail } = toRefs(props);

    const clock = ref();
    const title = ref("验证邮箱");
    // 发送验证码文本内容
    const content = ref('点击发送');
    // 发送验证码倒计时长
    const totalTime = ref(60);
    // 是否允许点击事件
    const canClick = ref(true);
    // 检查旧邮箱表单信息
    const checkOldEmailForm = reactive({
        code: "",
        key: "",
        rules: {
            code: [
                { required: true, message: '验证码不能为空', trigger: 'blur' }
            ]
        }
    });
    // 校验用户是否存在
    const validateEmail = (rule: any, value: any, callback: any): void => {
        api.common.isExistUserInfo({ username: value }).then(response => {
            if(response.code === 1) {
                callback(new Error(response.msg));
            }else {
                callback();
            }
        });
    };
    // 检查新邮箱表单信息
    const checkNewEmailForm = reactive({
        email: "",
        code: "",
        rules: {
            code: [
                { required: true, message: '验证码不能为空', trigger: 'blur' }
            ],
            email: [
                { required: true, message: '邮箱不能为空', trigger: 'blur' },
                { required: true, pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式错误', trigger: 'blur' },
                { validator: validateEmail, trigger: 'blur' }
            ],
        }
    });
    // 绑定class样式
    const classObj = reactive({
        // 验证码点击按钮样式
        sendBtn: true,
        // 禁止点击按钮样式
        banBtn: false
    });
    // 切换步骤条
    const switchStepObj = reactive({
        oldEmailSteps: true,
        newEmailSteps: false
    });

    /**
     * 发送邮箱验证码
     * @param tos 邮箱
     * @param formEl 表单校验
     */
    const sendEmailCode = (formEl: FormInstance | undefined, tos?: string) => {
        // 如果为false，则不执行下面操作
        if(!canClick.value) {
            return false;
        }
        formEl && formEl.validateField('email', async (valid) => {
            if (valid) {
                // 发送邮箱
                api
                .common
                .toEmail({ tos })
                .then(response => {
                    if(response.code === 0) {
                        canClick.value = false;
                        classObj.sendBtn = false;
                        classObj.banBtn = true;
                        content.value = totalTime.value + "S后重新发送";
                        clock.value = window.setInterval(() => {
                            totalTime.value--;
                            content.value = totalTime.value + "S后重新发送";
                            if (totalTime.value < 0) {
                                //当倒计时小于0时清除定时器
                                window.clearInterval(clock.value);
                                content.value = "重新发送";
                                totalTime.value = 60;
                                canClick.value = true; 
                                classObj.sendBtn = true;
                                classObj.banBtn = false;
                            }
                        }, 1000);
                    }
                });
            }
        })
    }

    /**
     * 重置邮箱验证码
     */
    const resetEmailCode = () => {
        window.clearInterval(clock.value);
        content.value = "点击发送";
        totalTime.value = 60;
        canClick.value = true; 
        classObj.sendBtn = true;
        classObj.banBtn = false;
    }

    /**
     * 下一步事件
     * @param formEl 表单校验
     */
    const nextStep = async (formEl: FormInstance | undefined) => {
        if (!formEl) return;
        await formEl.validate((valid) => {
            if (valid) {
                // 验证老邮箱信息
                api
                .user
                .validateOldEmail({ code: checkOldEmailForm.code })
                .then(response => {
                    if(response.code === 0) {
                        switchStepObj.oldEmailSteps = false;
                        switchStepObj.newEmailSteps = true;
                        // 清空字段值
                        formEl.resetFields();
                        // 重置邮箱验证码
                        resetEmailCode();
                        title.value = "修改邮箱";
                    } else {
                        ElNotification({
                            title: '提示',
                            message: response.msg,
                            type: 'error'
                        })
                    }
                });
            }
        })
    }

    /**
     * 绑定邮箱
     * @param formEl 表单校验
     */
    const bindEmail = async (formEl: FormInstance | undefined) => {
        if (!formEl) return;
        await formEl.validate((valid) => {
            if (valid) {
                // 绑定邮箱
                api
                .user
                .bindEmail({ email: checkNewEmailForm.email, code: checkNewEmailForm.code })
                .then(response => {
                    if(response.code === 0) {
                        if(internalInstance) {
                            internalInstance.emit("close");
                        }
                        msg.success("绑定成功");
                        // 清空字段值
                        formEl.resetFields();
                    } else {
                        msg.error("绑定失败");
                    }
                });
            }
        })
    }

</script>
<template>
    <el-dialog v-model="visible" :title="title" width="320" draggable :lock-scroll="false" :close-on-click-modal="false">
        <div class="steps-bar checkOldEmail" v-show="switchStepObj.oldEmailSteps">
            <el-form :model="checkOldEmailForm" :rules="checkOldEmailForm.rules" ref="checkOldEmailFormRef" class="from-box">
                <el-form-item prop="email" style="display: none">
                    <el-input ></el-input>
                </el-form-item>
                <el-form-item prop="code">
                    <div class="old_email">
                        <span>原邮箱：</span>{{ oldEmail }}
                    </div>
                    <el-input
                        placeholder="请输入验证码"
                        maxlength='4'
                        v-model="checkOldEmailForm.code" 
                        autocomplete="off"
                        size="large"
                    >
                        <template #prefix>
                            <svg-icon href="#icon-code" width="14px" height="14px" fill="#a8abb2"></svg-icon>
                        </template>
                        <template #suffix>
                            <el-button class="code-text" :class="classObj" :disabled="!canClick" type="primary" @click="sendEmailCode(checkOldEmailFormRef)" link>{{ content }}</el-button>
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>
            <el-button style="width: 100%;" type="primary" @click="nextStep(checkOldEmailFormRef)">下一步</el-button>
        </div>
        <div class="steps-bar checkNewEmail" v-show="switchStepObj.newEmailSteps">
            <el-form :model="checkNewEmailForm" :rules="checkNewEmailForm.rules" ref="checkNewEmailFormRef" class="from-box">
                <el-form-item prop="email">
                    <el-input placeholder="请输入新的电子邮箱" :prefix-icon="Message" v-model="checkNewEmailForm.email" size="large"></el-input>
                </el-form-item>
                <el-form-item prop="code">
                    <el-input
                        placeholder="请输入验证码"
                        maxlength='4'
                        v-model="checkNewEmailForm.code" 
                        autocomplete="off"
                        size="large"
                    >
                        <template #prefix>
                            <svg-icon href="#icon-code" width="14px" height="14px" fill="#a8abb2"></svg-icon>
                        </template>
                        <template #suffix>
                            <el-button 
                                class="code-text" 
                                :class="classObj" 
                                :disabled="!canClick" 
                                type="primary" 
                                @click="sendEmailCode(checkNewEmailFormRef, checkNewEmailForm.email)" 
                                link
                            >{{ content }}</el-button>
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>
            <el-button style="width: 100%;" type="primary" @click="bindEmail(checkNewEmailFormRef)">提      交</el-button>
        </div>
    </el-dialog>
</template>
<style lang="css" scoped>
    .old_email {
        padding: 0 0 5px 0;
        font-weight: bold;
        color: #999;
    }

    .code-text {
        color: #0084ff;
    }
</style>